package org.deri.vor.mobilesensing.mobilesensor;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings.Secure;

public class LocationPushService extends Service {
	public String Id;
	private LocationManager lm;
	private Location location;
	
	String lat,lon;
	public void GPSDicovery(){
		lm 			= (LocationManager) getSystemService(Context.LOCATION_SERVICE);	
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, LocationListernerObject);
		location 	= lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);	
		if (location!= null){
			lat			= Double.toString(location.getLatitude());
			lon			= Double.toString(location.getLongitude());
		}
	}
	
	private LocationListener LocationListernerObject	=	new LocationListener(){
		long start_time;
		
		@Override
		public void onLocationChanged(Location location) {
			lat			= Double.toString(location.getLatitude());
			lon			= Double.toString(location.getLongitude());
				if ((System.currentTimeMillis() - start_time)>3*1000){
				sendGeoData();
				start_time = System.currentTimeMillis();
			}
		}

		@Override
		public void onProviderDisabled(String arg0) {}

		@Override
		public void onProviderEnabled(String arg0) {sendGeoData();}

		@Override
		public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
	};
	
	public void sendGeoData(){
		String url = "http://lsm.deri.ie/volvorace/oceanrace?api=update&" +
				"userId=" + Id + 
				"&lat=" + lat + 
				"&long=" + lon;
		
		try {
			URL Url	=	new URL(url);
			Url.openConnection();
			Url.openStream();
		
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}
		
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	@Override
	public void onCreate(){
		super.onCreate();
		Id	=	Secure.getString(getBaseContext().getContentResolver(), Secure.ANDROID_ID);	
	}
	
	@Override
	public int onStartCommand(Intent intent,  int flag,int startId) {
		super.onStartCommand(intent,START_FLAG_RETRY,startId);
		GPSDicovery();
		return START_STICKY;
	}
	
	@Override
	public void onDestroy(){
		lm.removeUpdates(LocationListernerObject);
		super.onDestroy();
	}
	
}
